<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/14
 * Time: 16:03
 */

namespace app\admin\controller;


use app\admin\lib\AdminController;
use app\admin\model\ApiResponse;
use app\api\model\DrawPercentageRecord;
use app\api\model\user\Users;
use app\common\model\BuyBill;
use app\common\model\UserCreditRecord;
use library\IntConvert;
use think\Db;
use think\Exception;
use think\Log;
use think\Request;

class User extends AdminController
{
    /**
     * 注册用户管理列表
     * @return array
     */
    public function list() {
        $form = $this->getAndCheckForm([
            ['rows','integer',],
            ['page','integer',],
        ]);
        $mobile = $form['mobile'] ?? null;

        $query = Db::table('users u');
        $query->join('agency_invite_user aiu','aiu.userid = u.id','LEFT');
        $query->join('agency_salesman s','aiu.salesman_id = s.id','LEFT');
        $query->join('agency a','a.id = s.agency_id','LEFT');
        $query->join('agency_salesman asm','asm.id=u.id','LEFT');
        $query->join('agency sa','sa.id = asm.agency_id','LEFT');

        if ($mobile && strlen($mobile) <= 11) {
            $query->where(function ($q) use ($mobile) {
                if (strlen($mobile)>=8){
                    $q->where('u.mobile', 'like', "$mobile%");
                } else {
                    $q->where('u.mobile', 'like', "$mobile%");
                    $q->whereOr('u.id', $mobile);
                }
            });
        }

        $query->field('u.id,u.mobile,u.nickname,u.regtime,u.credit,u.register_from,
        s.code invite_code,a.name invite_agency_name,
        asm.code sales_code,sa.name sales_agency_name');
        $query->order('id','desc');
        $query->page($form['page']??1,$form['rows']??10);

        $result = $query->paginate($form['rows'] ?? 10,true,[
            'page' => $form['page']??1
        ])->toArray();

        foreach ($result['data'] as & $datum) {
            $datum['regtime'] = date('Y-m-d H:i', $datum['regtime']);
            $datum['register_source'] = Users::$RegisterFromSources[$datum['register_from']]??null;
        }

        $result['code'] = 200;

        return $result;
    }

    public function statistic() {

        $numClient = Db::table('users')
            // ->where('register_from','=',Users::REGISTER_FROM_CLIENT)
            ->count();
        $numTourist = Db::table('users')
            ->where('register_from','=',Users::REGISTER_FROM_IOS_TOURIST)
            ->count();

        return ApiResponse::success([
            'client' => number_format($numClient),
            'tourist' => $numTourist,
        ]);
    }

    /**
     * 添加用户
     *
     * @return ApiResponse
     */
    private function put() {
        $form = $this->getAndCheckForm([
            ['mobile', 'require|integer',],
            ['realname','chsAlpha',],
        ]);

        Db::transaction(function () use ($form) {
            Users::addUserIfNonExists($form['mobile'],'NOT-ACTIVE',$form['realname']??null,
                $form['nickname']??null,Users::REGISTER_FROM_ADMIN);

        });
        return ApiResponse::success();
    }

    public function index(Request $request) {
        if ($request->isGet()) return $this->list();
        if ($request->isPut()) return $this->put();

        return json(null,'405');
    }

    /**
     * save
     * 手动创建掌乾新用户
     *
     * @return ApiResponse
     * @throws \think\exception\DbException
     */
    public function save()
    {
        $form = $this->getAndCheckForm([
            ['password', 'require|length:6,255', '密码不能为空|密码长度不能小于6位'], // 密码
            ['mobile', 'require|number|length:11', '密码不能为空|密码长度不能小于6位'], // 密码
        ]);
        $id=$form['mobile']??0;
        if (isset($form['mobile']) && $id==0) {
            $res = Users::get(['mobile' => $form['mobile']]);
            if ($res) return ApiResponse::error(ApiResponse::ERR_EXISTS, '该账号已存在！');
        }

        $formData = [
            'password' => passEncrypt($form['password']),
        ];

        if (isset($form['id']) && $form['id']>0) { // 编辑用户
            try {
                if (isset($form['mobile'])) $formData['mobile'] = $form['mobile'];
                if(isset($form['nickname']) && $form['nickname']) $formData['nickname'] = $form['nickname'];
                Users::where('id', $form['id'])->update($formData);

                return ApiResponse::success();
            } catch (\Exception $e) {
                Log::error($e->getMessage());
                return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED, '用户更新失败');
            }
        } else {  // 添加用户
            try {
                if (isset($form['mobile'])) $formData['mobile'] = $form['mobile'];
                if(isset($form['nickname']) && $form['nickname']) $formData['nickname'] = $form['nickname'];
                $formData['regtime'] = time();
                $formData['register_from'] = Users::REGISTER_FROM_ADMIN;
                $model=new Users();
                $res=$model->data($formData)->save();
                // 生成邀请码
                Users::updateForExtensionCode($res->id, IntConvert::toString($res->id));

                // 生成技能雷达图数据
                Users::set_user_ability($res->id);
                // 注册送积分
                Users::creditTask($res->id, UserCreditRecord::CHANGE_TYPE_REGISTER);
                // 注册送课程
                BuyBill::addBillGift($res->id);

                return ApiResponse::success();
            } catch (\Exception $e) {
                Log::error($e->getMessage());
                return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED, '用户添加失败');
            }
        }
    }


    public function invitedUsersList()
    {
        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
            ['user_id', 'require|integer'],
        ]);
        $page = $form['page'] ?? 1;
        $limit = $form['rows'] ?? 10;
        $condition['promoter_id'] = $form['user_id'];
        if(isset($form['mobile'])){
            $condition['mobile']=['like','%'.$form['mobile'].'%'];
        }
        $list = Users::invitedUserList($condition, $page, $limit, $order = 'regtime desc', $filed = 'id,regtime,mobile,nickname,credit,register_from');
        if ($list) {
            foreach ($list as &$item) {
                $item->mobile = mobile_hidden($item->mobile);
                $item->regdate = date('Y-m-d H:i', $item->regtime);
                $item->register_source = Users::$RegisterFromSources[$item->register_from]??null;
            }
        }
        $result=[
            'list'=>$list,
            'total' => Users::invitedUserCount(['promoter_id' => $form['user_id']]),//一共邀请用户总数
        ];
        $result['total_page']=$limit>0 ? ceil($result['total']/$limit) : 0;
        return ApiResponse::success($result);
    }

    public function inviterdOrder(){
        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
            ['user_id', 'require|integer'],
        ]);
        $page = $form['page'] ?? 1;
        $limit = $form['rows'] ?? 10;
        $condition['d.promoter_id'] = $form['user_id'];
        $result = DrawPercentageRecord::getRecordListPage($condition, $page, $limit, $order = 'bill_paytime desc');
        return ApiResponse::success($result);
    }

    public function companyList() {
        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
        ]);
        $form['page'] = $form['page'] ?? 1;
        $rows = $form['rows'] ?? 10;
        $company_list=config('company_list');
        $mobiles=array_keys($company_list);
        $data=Users::getCompanyUser($condition=['mobile'=>['in',$mobiles]],$rows,'id,mobile,nickname');
        $form['month'] = $form['month'] ?? date('Y-m');
        $regtime=['between',[strtotime($form['month']),strtotime("+1 months", strtotime($form['month']))]];
        foreach($data['data'] as &$item){
            $item['name']=$company_list[$item['mobile']]??'';
            $item['invited_users_count']=Users::invitedUserCount(['promoter_id'=>$item['id'],'regtime'=>$regtime]);
        }
        return ApiResponse::success($data);
    }
}